package com.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.order.domain.pojo.Order;
import com.order.domain.pojo.OrderOperationLog;
import com.order.enums.OrderOperationLogType;
import com.order.enums.OrderOperationType;
import com.order.mapper.OrderOperationLogMapper;
import com.order.service.IOrderOperationLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

/**
 * <p>
 * 订单操作记录表 服务实现类
 * </p>
 *
 * @author 小杰大人
 * @since 2025-10-19
 */
@Service
public class OrderOperationLogServiceImpl extends ServiceImpl<OrderOperationLogMapper, OrderOperationLog> implements IOrderOperationLogService {

    @Override
    @Transactional
    public void add(Long orderId, String orderNo, OrderOperationLogType orderOperationLogType, Long operatorId, OrderOperationType orderOperationType, Object params) {
        OrderOperationLog orderOperationLog = OrderOperationLog.builder()
                .orderId(orderId)
                .orderNo(orderNo)
                .type(orderOperationLogType.getCode())
                .operationDesc(orderOperationLogType.getMessage())
                .operatorId(operatorId)
                .operatorType(orderOperationType.getCode())
                .operationParams(JSONObject.toJSONString(params))
                .ipAddress(getRealIpAddress())
                .createTime(LocalDateTime.now())
                .build();
        save(orderOperationLog);
    }

    public String getRealIpAddress() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            return "";
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("X-Real-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
}
